﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace BTSDecompress
{
    public partial class PredefinedQueryDialog : Form
    {
        #region Properties
        public string FileName
        { get; set; }
        public Hashtable Parameters
        { get; set; }
        #endregion
        #region Constructors
        public PredefinedQueryDialog()
        {
            InitializeComponent();
        }
        #endregion
        #region Methods
        private void LoadDatabases(string dataBaseServer)
        {
            //log.Debug(string.Format("BEGIN - {0}", System.Reflection.MethodInfo.GetCurrentMethod().ToString()));

            // Initialize the connection string
            String connString = String.Format("Data Source={0}; Integrated Security=True;", dataBaseServer);

            // Clear the list
            databasesComboBox.Items.Clear();
            try
            {
                // Initialize the connection
                using (SqlConnection cn = new SqlConnection(connString))
                {
                    // Retrieve the databases
                    cn.Open();
                    DataTable tblDatabases = cn.GetSchema("Databases");
                    cn.Close();

                    // Fill the combobox with the databases
                    foreach (DataRow row in tblDatabases.Rows)
                    {
                        string db = row["database_name"].ToString();
                        databasesComboBox.Items.Add(db);
                    }
                }
                //databasesComboBox.SelectedItem = "BizTalkMsgBoxDb";

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "BTSDecompress", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //log.Debug(string.Format("END - {0}", System.Reflection.MethodInfo.GetCurrentMethod().ToString()));
        }
        private void LoadHosts(string dataBaseServer)
        {
            //log.Debug(string.Format("BEGIN - {0}", System.Reflection.MethodInfo.GetCurrentMethod().ToString()));

            // Initialize the connection string
            String connString = String.Format("Data Source={0}; Initial Catalog=BizTalkMgmtDb; Integrated Security=True;", dataBaseServer);

            // Clear the list
            hostComboBox.Items.Clear();
            try
            {
                // Initialize the connection
                using (SqlConnection cn = new SqlConnection(connString))
                {
                    SqlCommand sqlCommand = new SqlCommand("select name from adm_host order by name",cn);
                    // Retrieve the databases
                    cn.Open();
                    SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();

                    // Fill the combobox with the databases
                    while (sqlDataReader.Read())
                    {
                        string host = sqlDataReader["name"].ToString();
                        hostComboBox.Items.Add(host);
                    }
                    cn.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "BTSDecompress", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //log.Debug(string.Format("END - {0}", System.Reflection.MethodInfo.GetCurrentMethod().ToString()));
        }
        private void LoadPredefinedQueries()
        { 
            // Open XML file which contains the predefined queries
            XmlDocument xmldocument = new XmlDocument();
            xmldocument.Load("predefinedqueries.xml");

            // Load the root nodes
            TreeNode MessageBoxNode = queriesTreeView.Nodes["MessageBoxQueries"];
            TreeNode TrackingDbNode = queriesTreeView.Nodes["TrackingDatabaseQueries"];

            // Iterate through all nodes and fil the TreeView
            foreach (XmlNode node in xmldocument.SelectSingleNode("//predefined"))
            {
                int category = Convert.ToInt16(node.Attributes["category"].InnerText);
                string name = node.FirstChild.InnerText;

                TreeNode treeNode = new TreeNode();
                treeNode.Text = name;
                treeNode.Tag = node.OuterXml;

                switch (category)
                {
                    case 1:
                    {
                        MessageBoxNode.Nodes.Add(treeNode);
                        break;
                    }
                    case 2:
                    {
                        TrackingDbNode.Nodes.Add(treeNode);
                        break;
                    }
                }
            }
        }
        private void SetProperties()
        {
            try
            {
                TreeNode node = queriesTreeView.SelectedNode; 
                
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(Convert.ToString(node.Tag.ToString()));
                FileName = xmlDocument.SelectSingleNode("query/location").InnerText;

                Hashtable hashTable = new Hashtable();

                foreach (XmlNode xmlNode in xmlDocument.SelectSingleNode("query/parameters"))
                {
                    switch (xmlNode.Attributes["name"].InnerText)
                    {
                        case "databaseserver":
                        {
                            hashTable.Add("databaseserver", databaseServerTextBox.Text);
                            break;
                        }
                        case "database":
                        {
                            hashTable.Add("database", databasesComboBox.Text);
                            break;
                        }
                        case "host":
                        {
                            hashTable.Add("host", hostComboBox.Text);
                            break;
                        }
                        case "instanceid":
                        {
                            hashTable.Add("instanceid", instanceIdTextBox.Text);
                            break;
                        }
                    }
                }
                Parameters = hashTable;
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
        }
        private void ShowQueryDetails(TreeNode node)
        {
            if (node.Tag != null)
            {
                try
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(Convert.ToString(node.Tag.ToString()));

                    nameLabel.Text = xmlDocument.SelectSingleNode("query/name").InnerText;
                    locationLabel.Text = xmlDocument.SelectSingleNode("query/location").InnerText;
                    descriptionLabel.Text = xmlDocument.SelectSingleNode("query/description").InnerText;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                nameLabel.Text = "";
                locationLabel.Text = "";
                descriptionLabel.Text = "";
            }
        }
        #endregion
        #region Events
        private void PredefinedQueryDialog_Load(object sender, EventArgs e)
        {
            LoadPredefinedQueries();
        }
        private void databasesComboBox_Enter(object sender, EventArgs e)
        {
            LoadDatabases(databaseServerTextBox.Text);
        }
        private void hostComboBox_Enter(object sender, EventArgs e)
        {
            LoadHosts(databaseServerTextBox.Text);
        }
        private void okButton_Click(object sender, EventArgs e)
        {
            SetProperties();
        }
        private void queriesTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeView treeview = (TreeView)sender;
            TreeNode node = treeview.SelectedNode;
            ShowQueryDetails(node);
        }
        #endregion

    }
}
